<?php
include('./inc/master.php');

// Check to see if we're receiving this request via Ajax.
if (isset($_POST['lastID'])) {
  $response = array('lastID' => -1, 'qas' => array());
  
  // Insert the QA into the database.
  $aid = 1; // TODO: Replace with something that reads the WP ID# of the current user.
  $db->query("INSERT INTO qa SET question = '". $_POST['question'] ."', answer = '". $_POST['answer'] ."', source = '". $_POST['source'] ."', aid = ". $aid);
  $iid = $db->insert_id;
  
  // Process the keywords.
  $keywords = explode(',', $_POST['keywords']);
  foreach ($keywords as $keyword) {
    $k = explode(':', $keyword);
    $db->query("INSERT INTO keywords SET keyword = '". $k[0] ."', frequency = ". $k[1] .", qaid = ". $iid);
  }
  
  // Prepare the response object.
  // Fetch the latest QAs.
  if ($result = $db->query("SELECT id, question, answer, source, aid, UNIX_TIMESTAMP(`happened`) FROM qa WHERE id > ". $_POST['lastID'] ." ORDER BY id ASC")) {
    
    while ($row = $result->fetch_row()) {
      // Update the lastID.
      $response['lastID'] = $row[0];
      
      // Add the QA to the list.
      // TODO: Replace default-profile.jpg with the author's WP avatar.
      $response['qas'][] = array('question' => stripslashes($row[1]), 'answer' => stripslashes($row[2]), 'source' => stripslashes($row[3]), 'profile_pic' => 'default-profile.jpg', 'timestamp' => date('M. j, Y, g:iA', $row[5]));
    }
    
    $result->close();
  }
  
  echo json_encode($response);
  
} else {

}

exit();
?>
